package models

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func GetGoods(GoodParam map[string]interface{}) (error, []Good, int64) {
	var Message []Good
	page := GoodParam["page"].(int) //返回数据格式
	pageSize := GoodParam["limit"].(int)
	searchText := GoodParam["searchText"].(string)
	fmt.Println(page, pageSize, searchText)
	var total int64
	err := db.Table("goods").Where("gid like ?", "%"+searchText+"%").Offset((page - 1) * pageSize).Limit(pageSize).Find(&Message).Count(&total).Error //从数据库中查询信息

	return err, Message, total
}

func AddGoods(c *gin.Context) (error, Good) { //添加货物
	var goodData Good
	err := c.ShouldBindJSON(&goodData) //货物添加的货物信息
	if err != nil {
		fmt.Println(err.Error()) //后端查看错误
	}

	err = db.Table("goods").Select("gid", "num", "car").Create(&goodData).Error //添加货物数据库操作
	return err, goodData
}

func UpGoods(c *gin.Context) (error, Good) { //更新货物
	var goodData Good
	err := c.ShouldBindJSON(&goodData) //信息绑定到结构体中

	err = db.Table("goods").Where("gid = ?", goodData.Gid).Updates(&goodData).Error
	return err, goodData
}

func DelGoods(c *gin.Context) error { //删除货物
	var goodData Good
	err := c.ShouldBindJSON(&goodData)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println(goodData)
	err = db.Debug().Table("goods").Where("gid = ?", goodData.Gid).Delete(&goodData).Error //将货物从数据库中删除
	return err
}
